/**
 * 项目管理页面 - 展示和查询所有PingCode项目
 */

'use client';

import React, { useState, useCallback, useEffect } from 'react';
import Link from 'next/link';
import {
  Layout,
  Space,
  Button,
  message,
  Card,
  Row,
  Col,
  Typography,
  Input,
  Select,
  Tag,
  Table,
  Pagination,
  DatePicker,
  Empty,
  Modal,
  Descriptions,
} from 'antd';
import {
  ReloadOutlined,
  SearchOutlined,
  ProjectOutlined,
  CalendarOutlined,
  TeamOutlined,
  EyeOutlined,
  DownloadOutlined,
  FileExcelOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { pingCodeAPI } from '../../utils/pingcodeApi';
import { ExportUtils } from '../../utils/exportUtils';
import ProjectExportModal from '../../components/ProjectExportModal';
import type { Project } from '../../types/workItem';
import dayjs from 'dayjs';

const { Content } = Layout;
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

export default function ProjectManagePage() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [searchParams, setSearchParams] = useState({
    name: '',
    type: undefined as string | undefined,
    dateRange: [] as any[],
  });
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [allProjects, setAllProjects] = useState<Project[]>([]);

  // 项目类型映射
  const projectTypeMap: Record<string, { text: string; color: string }> = {
    scrum: { text: 'Scrum', color: 'blue' },
    kanban: { text: '看板', color: 'green' },
    waterfall: { text: '瀑布', color: 'orange' },
    hybrid: { text: '混合', color: 'purple' },
  };

  // 状态映射
  const projectStateMap: Record<string, { text: string; color: string }> = {
    pending: { text: '待处理', color: 'default' },
    in_progress: { text: '进行中', color: 'processing' },
    completed: { text: '已完成', color: 'success' },
  };

  // 获取项目列表
  const fetchProjects = useCallback(async (params: any = {}) => {
    setLoading(true);
    try {
      console.log('获取项目列表，参数:', params);
      
      // 构造API参数
      const apiParams: any = {
        page_index: params.page_index || currentPage,
        page_size: params.page_size || pageSize,
      };

      // 添加搜索条件
      if (params.name) {
        apiParams.name = params.name;
      }
      
      if (params.type) {
        apiParams.type = params.type;
      }

      const response = await pingCodeAPI.getProjects(apiParams);
      console.log('获取项目列表成功:', response);
      
      setProjects(response.values || []);
      setTotal(response.total || 0);
      
      // 如果当前页没有数据且总数大于0，自动跳转到第一页
      if ((!response.values || response.values.length === 0) && response.total > 0 && currentPage > 1) {
        setCurrentPage(1);
      }
    } catch (error) {
      console.error('获取项目列表失败:', error);
      message.error(`获取项目列表失败: ${error instanceof Error ? error.message : '未知错误'}`);
      setProjects([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [currentPage, pageSize]);

  // 获取全部项目数据（用于导出）
  const fetchAllProjects = useCallback(async (searchFilters: any = {}) => {
    setExportLoading(true);
    try {
      console.log('获取全部项目数据用于导出');
      
      const allProjectsData: Project[] = [];
      let currentPageIndex = 1;
      const batchSize = 100; // 每次获取100条
      
      while (true) {
        const apiParams: any = {
          page_index: currentPageIndex,
          page_size: batchSize,
        };

        // 添加搜索条件
        if (searchFilters.name) {
          apiParams.name = searchFilters.name;
        }
        
        if (searchFilters.type) {
          apiParams.type = searchFilters.type;
        }

        const response = await pingCodeAPI.getProjects(apiParams);
        
        if (response.values && response.values.length > 0) {
          allProjectsData.push(...response.values);
          
          // 如果获取的数据少于批次大小，说明已经是最后一页
          if (response.values.length < batchSize) {
            break;
          }
          
          currentPageIndex++;
        } else {
          break;
        }
      }
      
      console.log(`成功获取全部项目数据，共 ${allProjectsData.length} 条`);
      setAllProjects(allProjectsData);
      return allProjectsData;
    } catch (error) {
      console.error('获取全部项目数据失败:', error);
      message.error(`获取全部项目数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
      return [];
    } finally {
      setExportLoading(false);
    }
  }, []);

  // 页面加载时获取数据
  useEffect(() => {
    fetchProjects();
  }, [fetchProjects]);

  // 处理搜索
  const handleSearch = () => {
    const params: any = {
      page_index: 1,
      page_size: pageSize,
    };
    
    if (searchParams.name) {
      params.name = searchParams.name;
    }
    
    if (searchParams.type) {
      params.type = searchParams.type;
    }
    
    setCurrentPage(1);
    fetchProjects(params);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({
      name: '',
      type: undefined,
      dateRange: [],
    });
    setCurrentPage(1);
    fetchProjects({ page_index: 1, page_size: pageSize });
  };

  // 刷新数据
  const handleRefresh = () => {
    console.log('手动刷新项目数据');
    fetchProjects();
  };

  // 处理分页变化
  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    fetchProjects({ page_index: page, page_size: size });
  };

  // 查看项目详情
  const handleViewProject = (project: Project) => {
    setSelectedProject(project);
    setDetailModalVisible(true);
  };

  // 关闭详情模态框
  const handleDetailModalClose = () => {
    setDetailModalVisible(false);
    setSelectedProject(null);
  };

  // 打开导出模态框
  const handleOpenExportModal = async () => {
    setExportModalVisible(true);
    
    // 获取当前搜索条件
    const searchFilters: any = {};
    if (searchParams.name) {
      searchFilters.name = searchParams.name;
    }
    if (searchParams.type) {
      searchFilters.type = searchParams.type;
    }
    
    // 获取全部项目数据
    await fetchAllProjects(searchFilters);
  };

  // 关闭导出模态框
  const handleCloseExportModal = () => {
    setExportModalVisible(false);
  };

  // 导出成功回调
  const handleExportSuccess = (count: number) => {
    message.success(`成功导出 ${count} 条项目数据`);
    setExportModalVisible(false);
  };

  // 表格列定义
  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Project) => (
        <Space>
          <ProjectOutlined />
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: '标识符',
      dataIndex: 'identifier',
      key: 'identifier',
      render: (text: string) => (
        <Tag color="default">{text}</Tag>
      ),
    },
    {
      title: '项目类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeInfo = projectTypeMap[type] || { text: type, color: 'default' };
        return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
      },
      filters: [
        { text: 'Scrum', value: 'scrum' },
        { text: '看板', value: 'kanban' },
        { text: '瀑布', value: 'waterfall' },
        { text: '混合', value: 'hybrid' },
      ],
      onFilter: (value: boolean | React.Key, record: Project) => record.type === value,
    },
    {
      title: '状态',
      dataIndex: ['state', 'name'],
      key: 'state',
      render: (text: string, record: Project) => {
        const stateType = record.state?.type || 'pending';
        const stateInfo = projectStateMap[stateType] || { text, color: 'default' };
        return <Tag color={stateInfo.color}>{stateInfo.text}</Tag>;
      },
    },
    {
      title: '负责人',
      dataIndex: ['assignee', 'display_name'],
      key: 'assignee',
      render: (text: string) => (
        <Space>
          <TeamOutlined />
          {text || '未分配'}
        </Space>
      ),
    },
    {
      title: '创建人',
      dataIndex: ['created_by', 'display_name'],
      key: 'created_by',
      render: (text: string) => (
        <Space>
          <TeamOutlined />
          {text || '未知'}
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (timestamp: number) => (
        <Space>
          <CalendarOutlined />
          {timestamp ? dayjs(timestamp * 1000).format('YYYY-MM-DD') : '-'}
        </Space>
      ),
      sorter: (a: Project, b: Project) => (a.created_at || 0) - (b.created_at || 0),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Project) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewProject(record)}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Content className="p-6">
        <div className="max-w-full mx-auto space-y-6">
          {/* 页面标题和操作按钮 */}
          <div className="flex justify-between items-center">
            <div>
              <Title level={2} className="!mb-0">
                项目管理
              </Title>
              <div className="text-sm text-gray-500 mt-1">
                API URL: {process.env.NEXT_PUBLIC_PINGCODE_API_URL || '未配置'} | 
                Token: {process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN ? 
                  `${process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN.substring(0, 8)}...` : '未配置'}
              </div>
            </div>
            <Space>
              <Link href="/work-items">
                <Button icon={<ProjectOutlined />}>
                  工作项管理
                </Button>
              </Link>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                loading={loading}
              >
                刷新
              </Button>
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                onClick={handleOpenExportModal}
                loading={exportLoading}
              >
                导出全部项目报表
              </Button>
            </Space>
          </div>

          {/* 查询表单 */}
          <Card title="查询条件" size="small">
            <Row gutter={[16, 16]}>
              <Col span={6}>
                <Input
                  placeholder="项目名称"
                  prefix={<SearchOutlined />}
                  value={searchParams.name}
                  onChange={(e) => setSearchParams({...searchParams, name: e.target.value})}
                  onPressEnter={handleSearch}
                />
              </Col>
              <Col span={6}>
                <Select
                  placeholder="项目类型"
                  style={{ width: '100%' }}
                  value={searchParams.type}
                  onChange={(value) => setSearchParams({...searchParams, type: value})}
                  allowClear
                >
                  <Option value="scrum">Scrum</Option>
                  <Option value="kanban">看板</Option>
                  <Option value="waterfall">瀑布</Option>
                  <Option value="hybrid">混合</Option>
                </Select>
              </Col>
              <Col span={12}>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                    查询
                  </Button>
                  <Button onClick={handleReset}>
                    重置
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>

          {/* 项目表格 */}
          <Card 
            title={
              <Space>
                <span>{`项目列表 (第${currentPage}页，共${projects.length}条，总计: ${total})`}</span>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  • 导出功能将导出全部 {total} 个项目的完整数据
                </Text>
              </Space>
            }
            extra={
              <Space>
                <Text type="secondary">
                  每页显示: 
                  <Select 
                    size="small" 
                    value={pageSize} 
                    onChange={(value) => {
                      setPageSize(value);
                      handlePageChange(1, value);
                    }}
                    className="ml-2"
                  >
                    <Option value={10}>10</Option>
                    <Option value={20}>20</Option>
                    <Option value={50}>50</Option>
                    <Option value={100}>100</Option>
                  </Select>
                </Text>
              </Space>
            }
            styles={{ body: { padding: 0 } }}
          >
            <Table
              dataSource={projects}
              columns={columns}
              loading={loading}
              pagination={false}
              rowKey="id"
              locale={{
                emptyText: (
                  <Empty 
                    description="暂无项目数据" 
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                )
              }}
            />
            <div className="p-4 flex justify-end">
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                onChange={handlePageChange}
                showSizeChanger={false}
                showQuickJumper
                showTotal={(total) => `共 ${total} 条记录`}
              />
            </div>
          </Card>
        </div>
      </Content>

      {/* 项目详情模态框 */}
      <Modal
        title="项目详情"
        open={detailModalVisible}
        onCancel={handleDetailModalClose}
        footer={[
          <Button key="close" onClick={handleDetailModalClose}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedProject && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="项目名称">{selectedProject.name}</Descriptions.Item>
            <Descriptions.Item label="标识符">{selectedProject.identifier}</Descriptions.Item>
            <Descriptions.Item label="项目类型">
              <Tag color={projectTypeMap[selectedProject.type]?.color || 'default'}>
                {projectTypeMap[selectedProject.type]?.text || selectedProject.type}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={projectStateMap[selectedProject.state?.type]?.color || 'default'}>
                {projectStateMap[selectedProject.state?.type]?.text || selectedProject.state?.name}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="可见性">
              <Tag color={selectedProject.visibility === 'public' ? 'blue' : 'gray'}>
                {selectedProject.visibility === 'public' ? '公开' : '私有'}
              </Tag>
            </Descriptions.Item>
            {selectedProject.assignee && (
              <Descriptions.Item label="负责人">
                {selectedProject.assignee.display_name}
              </Descriptions.Item>
            )}
            <Descriptions.Item label="创建人">
              {selectedProject.created_by?.display_name || '未知'}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {selectedProject.created_at ? dayjs(selectedProject.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {selectedProject.updated_at ? dayjs(selectedProject.updated_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Descriptions.Item>
            {selectedProject.start_at && (
              <Descriptions.Item label="开始时间">
                {dayjs(selectedProject.start_at * 1000).format('YYYY-MM-DD')}
              </Descriptions.Item>
            )}
            {selectedProject.end_at && (
              <Descriptions.Item label="结束时间">
                {dayjs(selectedProject.end_at * 1000).format('YYYY-MM-DD')}
              </Descriptions.Item>
            )}
            <Descriptions.Item label="是否归档">
              <Tag color={selectedProject.is_archived ? 'orange' : 'green'}>
                {selectedProject.is_archived ? '已归档' : '未归档'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="是否删除">
              <Tag color={selectedProject.is_deleted ? 'red' : 'green'}>
                {selectedProject.is_deleted ? '已删除' : '未删除'}
              </Tag>
            </Descriptions.Item>
            {selectedProject.description && (
              <Descriptions.Item label="描述">
                {selectedProject.description}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      {/* 项目导出模态框 */}
      <ProjectExportModal
        visible={exportModalVisible}
        onCancel={handleCloseExportModal}
        projects={allProjects}
        loading={exportLoading}
        searchFilters={{
          name: searchParams.name,
          type: searchParams.type,
        }}
      />
    </Layout>
  );
}